package com.robotic.minio;

import io.minio.*;
import io.minio.errors.*;
import io.minio.http.Method;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

@Service
@Slf4j
public class MinioService {

    @Autowired
    private MinioClient minioClient;

    @Autowired
    private MinioProperties minioProperties;


    public String uploadFile(MultipartFile file) {
        try {
            String bucketName = minioProperties.getBucketName();

            // 检查存储桶是否存在，不存在则创建
            boolean found = minioClient.bucketExists(BucketExistsArgs.builder().bucket(bucketName).build());
            if (!found) {
                minioClient.makeBucket(MakeBucketArgs.builder().bucket(bucketName).build());
            }

            // 构造对象名称: "math/uuid-filename.ext"
            String originalFilename = file.getOriginalFilename();
            String fileExtension = "";
            if (originalFilename != null && originalFilename.contains(".")) {
                fileExtension = originalFilename.substring(originalFilename.lastIndexOf("."));
            }
            String uniqueFileName = UUID.randomUUID() + fileExtension;
            String objectName = "math/" + uniqueFileName;

            // 上传文件
            minioClient.putObject(
                    PutObjectArgs.builder()
                            .bucket(bucketName)
                            .object(objectName)
                            .stream(file.getInputStream(), file.getSize(), -1)
                            .contentType(file.getContentType())
                            .build()
            );

            // ★★★ 核心修改点：不再生成预签名URL ★★★
            // 我们手动拼接URL。这 *必须* 依赖 "safetyimg" 桶是公开的！

            // 1. 从配置中获取 MinIO 的端点 (e.g., "http://192.168.201.246:9000")
            //    注意: 这假设您的 minioProperties 中有 getEndpoint() 方法
            String endpoint = minioProperties.getEndpoint();

            // 2. 确保 endpoint 结尾没有斜杠
            if (endpoint.endsWith("/")) {
                endpoint = endpoint.substring(0, endpoint.length() - 1);
            }

            // 3. 拼接公开URL
            String publicUrl = endpoint + "/" + bucketName + "/" + objectName;

            log.info("文件上传成功！(假定桶为公开)");
            log.info("ObjectName: " + objectName);
            log.info("Public URL: " + publicUrl);

            return publicUrl; // 返回不带签名的URL
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

}
